package com.taorenqi.business.utils;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import Decoder.BASE64Decoder;

/**
 * Created by eric on 2017/9/20.
 */

public class Jiemi {

    /**
     * 解密
     *
     * @param src
     *            byte[]
     * @param
     *
     * @throws Exception
     */
    public static String GetDesDecrypt(String src) {
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom random = new SecureRandom();
            String password = "A2l0C1j5";// getMD5(GetDate(new Date(), 1,  1)).substring(0,8);
            // 创建一个DESKeySpec对象
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            // 创建一个密匙工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 将DESKeySpec对象转换成SecretKey对象
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, securekey, random);
            // 真正开始解密操作
            return new String(cipher.doFinal(GetBase64decodetobyte(src)));
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * Base64解码
     */
    public static byte[] GetBase64decodetobyte(String str) {

        try {
            byte[] bt = null;
            BASE64Decoder decoder = new BASE64Decoder();
            bt = decoder.decodeBuffer(str);
            return bt;
        } catch (IOException e) {
            return null;
        }

    }
}
